/*
http://www.test.com/abc/de/fg.php?id=1&url=http://www.test.com/index.html
http://www.ceshi.com/hi.jsp
ftp://ftp.ceshi.com/hi.jsp
http://www.hello.com/cw/hi.jsp?k=8
http://www.hi.com/jk/l.html?id=1&s=a.html
http://www.rs.com/n.op/q/rs?id=1
http://www.abc.com/
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define URL_MAX_LEN 256
#define MAX_FILENAME_LEN 50

typedef struct List{
	char* name;
	int count;
	struct List* next;
}list;

list* head;

void print_list(list* h){
	if(h==NULL)return;
	list* hh=h;
	for(;hh!=NULL;hh=hh->next){
		printf("%s=%d\n",hh->name,hh->count);
	}
}

void add_to_list(char* filename){
	list* h=head;
	list* last=head;
//	printf("find\n");
	for(;h!=NULL;last=h,h=h->next){
		if(strcmp(filename,h->name)==0){
			h->count++;
			return;
		}
	}
//	printf("no add \n");
	list* n=(list*)malloc(sizeof(list));
	n->name=strdup(filename);
	n->count=1;
	n->next=NULL;
	last->next=n;
}

void add_file(char* filename){
	printf("addfile:%s\n",filename);
	if(head==NULL){
		head=(list*)malloc(sizeof(list));
		head->next=NULL;
		head->count=1;
		head->name=strdup(filename);
		return;
	}
	add_to_list(filename);
}

void parse_url(char* url,int len){
	printf("url:%s\n",url);
	//find last /
	char* end=url+len;
	if( *end=='/'){
		add_file("empty");
		return;
	}
	
	char* qupos=end;
	for(;end!=url;end--){
//		printf("*end : %c",*end);
		if(*end=='?'){
			qupos=end;
		}else if(*end=='/'){
//			printf("\nfound :%c,%c\n",*end,*qupos);
			char* fnn=(char*)malloc(qupos-end);
			char* fn=fnn;
			for(end++;end<qupos;end++){
				*fn++=*end;
			}
			*fn=0;
			add_file(fnn);
			break;
		}
	}
}

void write_list(char* filename,list* head){
	FILE* fp=fopen(filename,"w+");
	list* h=head;
	for(;h!=NULL;h=h->next){
		fprintf(fp,"%s,%d\t",h->name,h->count);
	}
	fclose(fp);
}

list* read_list(char*filename){
	int count;
	char* name=(char*)malloc(256);
	FILE* fp=fopen(filename,"r");
	
	list* h;
	list* last;
	while(fscanf(fp,"%s,%d\t",name,count)!=EOF){
		h=(list*)malloc(sizeof(list));
		h->name=strdup(name);
		h->count=count;
		h->next=NULL;
		if(last==NULL){
			head=h;	
			last=h;
		}			
		else{
			last->next=h;
			last=h;
		}
	}
	
	fclose(fp);
	
	printf("read ok\n");
	print_list(head);
}

int main(){
	FILE* fp=fopen("urls.txt","r");
	char ch;
	char* buffer=(char*)malloc(URL_MAX_LEN);
	char* pb=buffer;
	
	while( (ch=fgetc(fp))!=EOF){
		*pb++=ch;
		ch=fgetc(fp);
		int len=0;
		while(ch!=EOF && ch!='\n'){
			*pb++=ch;
			len++;
			ch=fgetc(fp);
		} 
		*pb='\0';
		parse_url(buffer,len);
		pb=buffer;
	}
	fclose(fp);
	
	print_list(head);
	
	write_list("result.txt",head);
	read_list("result.txt");
}